package com.mobartisan.vehiclenetstore.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.mobartisan.vehiclenetstore.ECarApplication;
import com.mobartisan.vehiclenetstore.R;
import com.mobartisan.vehiclenetstore.constants.Constants;
import com.mobartisan.vehiclenetstore.constants.ReqeustCode;
import com.mobartisan.vehiclenetstore.getui_push.InformationReceiver;
import com.mobartisan.vehiclenetstore.getui_push.NotificitionManager;
import com.mobartisan.vehiclenetstore.ui.base.BaseActivity;
import com.mobartisan.vehiclenetstore.util.JsToJava;
import com.mobartisan.vehiclenetstore.util.SharedPreferencesUtil;
import com.mobartisan.vehiclenetstore.util.ToastUtils;

import butterknife.ButterKnife;

import static android.view.View.GONE;
import static android.view.View.VISIBLE;
import static com.mobartisan.vehiclenetstore.ECarApplication.payloadData;


public class MainActivity extends BaseActivity implements ReqeustCode {
    public static final String TAG = MainActivity.class.getSimpleName();

    public static final String APP_CACAHE_DIRNAME = "/webcache";
    WebView textWebview;
    SwipeRefreshLayout swipeRefreshLayout;
    ProgressBar progressbar;
    private long firstTime = 0;
    String url = "";
    //        String URL = "http://192.168.3.64:8089/main.html";
    private String on_off_push = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        ECarApplication.mainActivity = this;
        on_off_push = SharedPreferencesUtil.getInstance().getStringValue(Constants.On_Off_Push);
        Log.e(TAG, "===========+++++++++=" + on_off_push);
        initView();
        initData();
    }


    //通知刷新页面
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Bundle bundle = intent.getExtras();
        if (bundle != null) {
            Constants.URL = bundle.getString("url");
            Log.e(TAG, "===========+++++++++=" + Constants.URL);
            textWebview.loadUrl(Constants.URL);
        }
    }

    @Override
    public Activity getActivity() {
        return this;
    }


    @Override
    public void onBackPressed() {

        super.onBackPressed();

    }

    @SuppressLint("SetJavaScriptEnabled")
    @Override
    public void initView() {
        textWebview = (WebView) findViewById(R.id.textWebview);
        progressbar = (ProgressBar) findViewById(R.id.progress);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_webview);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                textWebview.clearCache(true);
                textWebview.clearFormData();
                textWebview.loadUrl(textWebview.getUrl());
            }
        });

        swipeRefreshLayout.setColorScheme(R.color.holo_blue_bright, R.color.holo_green_light, R.color.holo_orange_light, R.color.holo_red_light);
        WebSettings settings = textWebview.getSettings();
        settings.setJavaScriptEnabled(true);

        //设置支持获取手势焦点。
//        settings.setDefaultTextEncodingName("UTF-8");
        textWebview.requestFocusFromTouch();
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        settings.setAllowFileAccess(true);

        // 设置可以支持缩放
        settings.setSupportZoom(false);
        settings.setLoadsImagesAutomatically(true);
        //扩大比例的缩放
        settings.setUseWideViewPort(true);
        //自适应屏幕
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        settings.setLoadWithOverviewMode(true);
        //开启缓存机制
        settings.setAppCacheEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        textWebview.addJavascriptInterface(new JsToJava(), "echarge");
        textWebview.addJavascriptInterface(new JsToJava(), "switch");
        textWebview.addJavascriptInterface(MainActivity.this, "clear");

        textWebview.setWebViewClient(new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {


                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {

                super.onPageFinished(view, url);
                textWebview.loadUrl("javascript:postMsg()");
                on_off_push = SharedPreferencesUtil.getInstance().getStringValue(Constants.On_Off_Push);
                if (on_off_push.equals("onpush")) {
                    Log.i(TAG, "onPageFinished: =============");
                    textWebview.loadUrl("javascript:initMsg(" + "'onpush'" + ")");
                } else if (on_off_push.equals("offpush")) {
                    textWebview.loadUrl("javascript:initMsg(" + "'offpush'" + ")");
                }
                textWebview.loadUrl("javascript:initMsg()");
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                return super.shouldOverrideUrlLoading(view, request);
            }
        });
        textWebview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress >= 70) {
                    for (int i = 0; i < 100 - newProgress; i++) {
                        progressbar.setProgress(newProgress + i);
                    }
                    progressbar.setVisibility(GONE);
                    swipeRefreshLayout.setRefreshing(false);
                } else {
                    if (progressbar.getVisibility() == GONE)
                        progressbar.setVisibility(VISIBLE);
                    Log.d(TAG, "=============" + newProgress);
                    progressbar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }
        });
        textWebview.loadUrl(Constants.URL);


    }

    @Override
    public void initData() {
    NotificitionManager.showNofi(context, "", "提醒", payloadData, InformationReceiver.class);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && textWebview.canGoBack()) {
            textWebview.goBack();// 返回前一个页面
            return true;
        } else if (keyCode == KeyEvent.KEYCODE_BACK && !textWebview.canGoBack() && event.getAction() == KeyEvent.ACTION_DOWN) {
            long secondTime = System.currentTimeMillis();
            if (secondTime - firstTime > 2000) {
                ToastUtils.showShort(getString(R.string.toast_back_text));
                firstTime = secondTime;
                return true;
            } else {
                clearBuffer();
                ECarApplication.getInstance().exitApp();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        clearBuffer();
    }

    private void clearBuffer() {
        deleteDatabase("webview.db");
        deleteDatabase("webviewCache.db");
        textWebview.clearCache(true);
        textWebview.clearFormData();
    }

    @JavascriptInterface
    public void clearMethod() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Log.e(TAG, "run: ==========clearMethod");
                clearBuffer();
            }
        });


    }
}
